package com.ethercamp.harmony.dmt.db.config;

import com.ethercamp.harmony.dmt.db.core.SimpleAccount;
import com.ethercamp.harmony.dmt.db.handler.AccountObserver;
import com.ethercamp.harmony.dmt.db.handler.BlockObserver;
import com.ethercamp.harmony.dmt.db.handler.TransactionObserver;
import org.ethereum.config.SystemProperties;
import org.ethereum.core.Genesis;
import org.ethereum.core.Transaction;
import org.ethereum.util.ByteUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import java.util.ArrayList;
import java.util.List;

/**
 * 初始化mongodb
 */
public class Initializer {

    private final Logger logger = LoggerFactory.getLogger("initializer");


//    private MongoTemplate mongoTemplate;
//    private SystemProperties systemProperties = SystemProperties.getDefault();
//    private List<SimpleAccount> accounts = new ArrayList<>();

//    public Initializer(MongoTemplate mongoTemplate) {
//        this.mongoTemplate = mongoTemplate;
//        if (!this.mongoTemplate.exists(Query.query(Criteria.where("balance").gt(0)), "accounts")) {
//            init();
//        }
//    }
    private BlockObserver blockObserver;

    private TransactionObserver transactionObserver;

    private AccountObserver accountObserver;

    public Initializer(BlockObserver blockObserver, TransactionObserver transactionObserve, AccountObserver accountObserver) {
        this.blockObserver = blockObserver;
        this.transactionObserver = transactionObserve;
        this.accountObserver = accountObserver;
        init();
    }

    private void init() {
//        Genesis.getInstance(systemProperties).getTransactionsList().forEach(this::processTransaction);
        logger.info("init database");
        // 删除表
        blockObserver.dropBlock();
        transactionObserver.dropBlock();
        accountObserver.dropAccounts();

    }
//
//    private void processTransaction(Transaction tx) {
//        SimpleAccount account = new SimpleAccount();
//        account.setBalance(ByteUtil.bytesToBigInteger(tx.getValue()).doubleValue());
//        account.setAddress(ByteUtil.toHexString(tx.getReceiveAddress()));
//        account.setCode("");
//        account.setNonce(0);
//        accounts.add(account);
//        if (accounts.size() >= 1000) {
//            flush();
//        }
//    }
//
//    private void flush() {
//        mongoTemplate.insertAll(accounts);
//        accounts.clear();
//    }
}
